package net.wisos.opn.account.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import net.wisos.opn.account.entity.Role;
import net.wisos.opn.account.entity.User;

import org.springframework.stereotype.Component;

/**
 * RoleDao的扩展行为实现类.
 */
@SuppressWarnings("unchecked")
@Component
public class RoleDaoImpl implements RoleDaoCustom {

	private static final String QUERY_USER_BY_ROLEID = "select u from User u left join u.roles r where r.id=?";

	@PersistenceContext
	private EntityManager em;

	@Override
	public void deleteWithReference(Long id) {
		Role role = em.find(Role.class, id);
		List<User> users = em.createQuery(QUERY_USER_BY_ROLEID)
				.setParameter(1, id).getResultList();
		for (User u : users) {
			u.getRoles().remove(role);
		}
		em.remove(role);
	}

}
